//
//  UserCustomNavigationBar.m
//  Cloud189
//
//  Created by Liam on 12-7-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "UserCustomNavigationBar.h"

@interface UserCustomNavigationBar()

@property (nonatomic, retain) UINavigationItem               *observItem;

- (void)toPopViewController;

@end

@implementation UserCustomNavigationBar
@synthesize observItem      = _observItem;
@synthesize titleColor		= _titleColor;

- (void)dealloc{
	
	if(self.observItem != nil){
        [self.observItem removeObserver:self forKeyPath:@"title"];
        [self.observItem removeObserver:self forKeyPath:@"hidesBackButton"];
    }
	
    SAFE_RELEASE(_observItem);
	SAFE_RELEASE(_titleColor);
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
		self.titleColor = [UIColor whiteColor];
		self.backgroundImage = [UIImage imageNamed:@"wy_nav_bg.png"];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
	self = [super initWithCoder:aDecoder];
	if (self) {
        self.delegate = self;
		self.titleColor = [UIColor whiteColor];
		self.backgroundImage = [UIImage imageNamed:@"wy_nav_bg.png"];
		
		if (self.topItem)
		{
			[self navigationBar:self shouldPushItem:self.topItem];
		}
	}
	return self;
}

- (void)cutsomTitleViewForItem:(UINavigationItem *)item
{
	UILabel *label = nil;
	
	if (item.titleView == nil)
	{
		CGRect bounds = self.bounds;
		bounds.size.width = 200;
		
		label = [[[UILabel alloc] initWithFrame:bounds] autorelease];
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		label.lineBreakMode = UILineBreakModeTailTruncation;
		label.textColor = self.titleColor;
		[label setFont:[UIFont fontWithName:@"Helvetica" size:20]];
		item.titleView = label;
	}
	else if ([item.titleView isKindOfClass:[UILabel class]])
	{
		label = (UILabel *)item.titleView;
	}
	
	if (label)
	{
		label.textColor = self.titleColor;
		label.text = item.title;
	}
}

- (void)layoutSubviews
{
	[super layoutSubviews];
}

- (void)setTitleColor:(UIColor *)color
{
	SAFE_RELEASE(_titleColor)
	_titleColor = [color retain];
}

- (UINavigationItem *)popNavigationItemAnimated:(BOOL)animated
{
	if ([self.items count])
	{
		UINavigationItem * item = [self.items lastObject];
		animated = !item.hidesBackButton;
	}
	return [super popNavigationItemAnimated:animated];
}

- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated
{
	animated = !item.hidesBackButton;
	[super pushNavigationItem:item animated:animated];
}

- (void)setItems:(NSArray *)items
{
	[super setItems:items];
}

- (void)setItems:(NSArray *)items animated:(BOOL)animated
{
	if ([items count])
	{
		UINavigationItem * item = [items lastObject];
		animated = !item.hidesBackButton;
	}
	
	[super setItems:items animated:animated];
	
	if ([items count])
	{
		[self navigationBar:self shouldPushItem:[items lastObject]];
	}
}

- (void)toPopViewController{
    if([_outsideDelegate isKindOfClass:[UINavigationController class]]){
        [(UINavigationController*)_outsideDelegate  popViewControllerAnimated:YES]; 
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{    
    if([keyPath isEqualToString:@"title"] && [(UINavigationItem *)object title] != nil)
    {
		UINavigationItem * item = (UINavigationItem *)object;
		[self cutsomTitleViewForItem:item];
    }
    else if([keyPath isEqualToString:@"hidesBackButton"])
    {
        self.observItem.leftBarButtonItem.customView.hidden = ((UINavigationItem *)object).hidesBackButton;
    }
}

- (void)navigationBar:(UINavigationBar *)navigationBar didPushItem:(UINavigationItem *)item{ 
    
    if (_outsideDelegate && [_outsideDelegate respondsToSelector:@selector(navigationBar:didPushItem:)]){
		[_outsideDelegate navigationBar:navigationBar didPushItem:item];
	}
}

- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item{
    if (_outsideDelegate && [_outsideDelegate respondsToSelector:@selector(navigationBar:didPopItem:)]){
		[_outsideDelegate navigationBar:navigationBar didPopItem:item];
	}
}

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    if(self.observItem != nil){
        [self.observItem removeObserver:self forKeyPath:@"title"];
        [self.observItem removeObserver:self forKeyPath:@"hidesBackButton"];
    }
    
    int index = [self.items indexOfObject:item] - 1;
    
    if(index <self.items.count){
        if([self.items objectAtIndex:index]){
            self.observItem = [self.items objectAtIndex:index];
        }
    }
    
    if(self.observItem){
        [self.observItem addObserver:self forKeyPath:@"title"
                             options:0 context:NULL];
        [self.observItem addObserver:self forKeyPath:@"hidesBackButton"
                             options:0 context:NULL];
    }

    if (_outsideDelegate && [_outsideDelegate respondsToSelector:@selector(navigationBar:shouldPopItem:)]){
		return [_outsideDelegate navigationBar:navigationBar shouldPopItem:item];
	}
    return YES;
}

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item
{
	[self cutsomTitleViewForItem:item];
	if ([self.items count] && [self.items indexOfObject:item] != 0)
	{
		if (!item.hidesBackButton)
		{
			UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
			UIImage *image = [UIImage imageNamed:@"wy_nav_back_unfocus.png"];
			[button setImage:image forState:UIControlStateNormal];
			[button setImage:[UIImage imageNamed:@"wy_nav_back_focus.png"] forState:UIControlStateHighlighted];
			[button sizeToFit];
			float leftBtnWidth   = image.size.width;
			float leftBtnHeight  = button.frame.size.height;
			button.frame = CGRectMake(0, 0, leftBtnWidth, leftBtnHeight);
			[button addTarget:self action:@selector(toPopViewController) forControlEvents:UIControlEventTouchUpInside];
			item.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
		}
	}
    if(self.observItem != nil){
        [self.observItem removeObserver:self forKeyPath:@"title"];
        [self.observItem removeObserver:self forKeyPath:@"hidesBackButton"];
    }
    
    self.observItem = item;
    [self.observItem addObserver:self forKeyPath:@"title"
                         options:0 context:NULL];
    [self.observItem addObserver:self forKeyPath:@"hidesBackButton"
                         options:0 context:NULL];

    if (_outsideDelegate && [_outsideDelegate respondsToSelector:@selector(navigationBar:shouldPushItem:)]){
		return [_outsideDelegate navigationBar:navigationBar shouldPushItem:item];
	}
    
    return YES;
}

- (void)setDelegate:(id <UINavigationBarDelegate>)delegate
{
    NSLog(@"the self delegate is:%@",_outsideDelegate);
	if (delegate != self){
        _outsideDelegate = delegate;
    }
    else{
        _outsideDelegate = self.delegate;
    }
     NSLog(@"the self delegate is:%@",_outsideDelegate);
	[super setDelegate:self];
}


@end
